package com.twu.biblioteca.controllers;


import com.twu.biblioteca.models.Book;
import com.twu.biblioteca.models.BookDAO;

public final class ConsoleReturnBook extends Console {

    @Override
    public void run() {
        this.io.getOutput().delete(0, this.io.getOutput().length());
        this.io.getOutput().append("Enter book's id (enter 0 to return Main Menu): ");
        System.out.println(this.io.getOutput());

        String idBookHex = this.io.getInput().nextLine();

        if(idBookHex.equals("0")){
            this.io.getOutput().delete(0, this.io.getOutput().length());
            this.io.getOutput().append("\n\n");
            new ConsoleMainMenu().run();
        }
        else{
            Long idEnter = Long.parseLong(idBookHex, 16);

            Book book = new BookDAO().getBook(idEnter);

            this.io.getOutput().delete(0, this.io.getOutput().length());

            if(book == null || !book.isCheckout()){
                this.io.getOutput().append("That is not a valid book to return");

                this.io.getOutput().append("\n\n1- Return book the correct library\n2- Fix spelling error\n\nOption: ");

                System.out.println(this.io.getOutput());

                try {
                    byte option = Byte.parseByte(this.io.getInput().nextLine());

                    switch (option) {
                        case 1:
                            System.exit(0);
                            break;
                        case 2:
                            new ConsoleReturnBook().run();
                            break;
                        default:
                            System.out.println("\n\tSelect a valid option!");
                            new ConsoleReturnBook().run();
                    }
                }
                catch (NumberFormatException e){
                    System.out.println("\n\tSelect a valid option!");
                    new ConsoleReturnBook().run();
                }
            }
            else{
                this.io.getOutput().append("Return the book \"" + book.getName() + "\"(y/n)?");
                System.out.println(this.io.getOutput());
                this.io.getOutput().delete(0, this.io.getOutput().length());

                String option = this.io.getInput().nextLine();

                if(option.equals("y")){
                    book.setCheckout(false);
                    book.setUser(null);
                    System.out.println("Thank you for returning the book\n");
                    new ConsoleMainMenu().run();
                }
                else if(option.equals("n")){
                    new ConsoleReturnBook().run();
                }
                else{
                    System.out.println("\n\tSelect a valid option!\n");
                    new ConsoleReturnBook().run();
                }

                this.io.getOutput().append("Thank you for returning the book");

            }
        }
    }
}
